import { app } from 'electron'

const toString = Object.prototype.toString;

export function is(val, type) {
  return toString.call(val) === `[object ${type}]`;
}

export function isObject(val){
  return val !== null && is(val, 'Object');
}

export function isDef(val){
  return typeof val !== 'undefined';
}

export function isFunction(val){
  return typeof val === 'function';
}

export function isPromise(val){
  return is(val, 'Promise') && isObject(val) && isFunction(val.then) && isFunction(val.catch);
}

export const randomEncodeStr = (length = 12) => {
  const characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = '';

  for (let i = 0; i < length; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length);
      result += characters[randomIndex];
  }

  return result;
}

export const getUserAgent = (view) => {
  return view.webContents.getUserAgent()
    .replace(`Electron/${process.versions.electron} `, '')
    .replace(`${app.getName()}/${app.getVersion()} `, '')
}

export function convertStrCookieToDict(cookieStr) {
  const cookieDict = {};
  if (!cookieStr) {
      return cookieDict;
  }

  const cookies = cookieStr.split(';');

  cookies.forEach(cookie => {
    const trimmedCookie = cookie.trim();
    if (!trimmedCookie) {
      return;
    }
    const cookieParts = trimmedCookie.split('=');
    if (cookieParts.length !== 2) {
      return;
    }
    const cookieName = cookieParts[0];
    const cookieValue = cookieParts[1];
    cookieDict[cookieName] = cookieValue;
  });

  return cookieDict;
}

export const parseCookie = (cookieString) => {
  const cookieObj = {}

  const cookies = cookieString.split('; ');
  for (const cookie of cookies) {
    const [cookieName, cookieValue] = cookie.split('=');
    cookieObj[cookieName] = cookieValue
  }

  return cookieObj
}

export function parseProxyUrl(proxyUrl) {
  // 解析 URL
  const url = new URL(proxyUrl);

  // 提取信息
  const protocol = url.protocol.slice(0, -1); // 移除协议末尾的冒号
  const ip = url.hostname;
  const port = url.port;
  const user = url.username;
  const password = url.password;

  const proxyInfo = {
    protocol: protocol + '://',
    ip,
    port,
    user,
    password,
  };

  return proxyInfo;
}
  
export function formatProxyInfo(proxyInfo) {
  const playwrightProxy = {
    server: `${proxyInfo.protocol}${proxyInfo.ip}:${proxyInfo.port}`,
    username: proxyInfo.user,
    password: proxyInfo.password,
  };

  const httpsProxy = {
    host: proxyInfo.ip,
    port: proxyInfo.port,
    auth: {
      username: proxyInfo.user,
      password: proxyInfo.password,
    },
    protocol: 'http',
  };

  return [playwrightProxy, httpsProxy];
}

export const getTopLevelDomain = (url) => {
  const domainRegex = /^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/im;
  const matches = url.match(domainRegex);
  if (matches && matches.length >= 2) {
    const fullDomain = matches[1];
    const domainParts = fullDomain.split('.');
    let topLevelDomain = '';
    if (domainParts.length > 2) {
      topLevelDomain = domainParts.slice(-2).join('.');
    } else {
      topLevelDomain = fullDomain;
    }
    return topLevelDomain;
  }
  return null;
}
